package yicheng.dinnertogetherapp;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import yicheng.dinnertogetherapp.R;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.DragEvent;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView.OnEditorActionListener;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;
import android.widget.TextView;

public class MyInfoActivity extends Activity{
	public static Switch make_me_available_switch;
	private TextView make_me_available_textView, preference_textView; 
	public static TextView from_date_textView, until_date_textView;
	public static TextView preference_character_textView;
	private Button from_button, until_button, preference_button, me_button;
	public static PersonalPrefBackPressedEditText preference_editText;
	private RelativeLayout myInfo_linearLayout;

	private DatePicker date_picker;   
	private TimePicker time_picker;




	public static AmazonClientManager clientManager;

	public static SharedPreferences local_user_information;
	private SharedPreferences.Editor local_user_editor;
	private String PREFS_NAME = "LocalUserInfo";

	private String PRIMARY_PHONE_NUMBER;

	private String PHONE_NUMBER, NICKNAME;
	public static String PREFERENCE;
	private String START_TIME;
	private String END_TIME;
	private Date FROM_DATE;
	private Date UNTIL_DATE;
	private String ONLINE;
	private String s;






	private BroadcastReceiver broadcastReceiver;






	private Handler handler;

	private boolean isDataBaseUpgraded;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		clientManager = new AmazonClientManager();

		local_user_information =  this.getSharedPreferences(PREFS_NAME,0);




		setContentView(R.layout.my_info_view);

		make_me_available_textView = (TextView) findViewById(R.id.make_me_available_textView);
		from_date_textView = (TextView) findViewById(R.id.from_date_textView);
		until_date_textView = (TextView) findViewById(R.id.until_date_textView);



		//preference_textView = (TextView) findViewById(R.id.preference_textView);
		preference_character_textView = (TextView) findViewById(R.id.preference_character_textView);

		if (!isMyServiceRunning()){
			startService(new Intent(this, UserInfoUpdateService.class));
		}

		updateFromDateDisplay();

		//MyInfoActivity.this.stopService(new Intent(MyInfoActivity.this, BackgroundDateUpdateService.class));

		//startService(new Intent(this, UserInfoUpdateService.class));











		myInfo_linearLayout = (RelativeLayout) findViewById(R.id.myInfo_linear_layout);

		myInfo_linearLayout.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				updatePreferenceDisplay();
				hideKeyboard();
				return false;
			}
		});

		myInfo_linearLayout.requestFocus();



		preference_editText = (PersonalPrefBackPressedEditText) findViewById(R.id.preference_editText);



		preference_editText.setCursorVisible(false);

		preference_editText.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				preference_editText.setCursorVisible(true);
			}
		});


		preference_editText.setOnEditorActionListener(new OnEditorActionListener(){

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				// TODO Auto-generated method stub
				if (actionId == EditorInfo.IME_ACTION_DONE){

					AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MyInfoActivity.this);
					dialogBuilder.setTitle("Publish");


					dialogBuilder.setMessage("Publish your preference?");
					dialogBuilder.setCancelable(true);
					dialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {



							//local_user_information =  this.getSharedPreferences(PREFS_NAME,0);
							local_user_editor = local_user_information.edit();
							local_user_editor.putString("Preference", preference_editText.getText().toString());
							local_user_editor.commit();

							updatePreference();
							updatePreferenceDisplay();
							dialog.cancel();

						}
					});


					dialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							updatePreferenceDisplay();
							dialog.cancel();


						}
					});

					if (isConnectedToInternet()){
						AlertDialog dialog = dialogBuilder.create();
						dialog.show();
					}
					else{
						Toast.makeText(getApplicationContext(), "You are not conneceted to Internet, please check.", Toast.LENGTH_SHORT).show();
					}


					preference_editText.setCursorVisible(false);
				}
				return false;
			}

		});

		updatePreferenceDisplay();

		TextWatcher preference_editText_watcher = new TextWatcher(){

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub


			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				preference_character_textView.setText(String.valueOf(95 - s.length()));
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}

		};

		preference_editText.addTextChangedListener(preference_editText_watcher);






		make_me_available_switch = (Switch) findViewById(R.id.make_me_available_switch);

		updateOnlineSwitchDisplay();



		make_me_available_switch.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				make_me_available_switch.setOnCheckedChangeListener(new OnCheckedChangeListener(){
					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// TODO Auto-generated method stub



						if (isConnectedToInternet()){
							updateOnlineStatus(isChecked);
						}
						else{
							Toast.makeText(getApplicationContext(), "You are not conneceted to Internet, please check.", Toast.LENGTH_SHORT).show();
						}
					}

				});


				// TODO Auto-generated method stub
				if (isStartAndEndTimeBeforeNow()){

					make_me_available_switch.setEnabled(false);
					make_me_available_switch.setChecked(false);
					Toast.makeText(getBaseContext(), "Please set your start time a future time!", Toast.LENGTH_LONG).show();
				}

				return false;
			}
		});











		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 1){
					make_me_available_switch.setEnabled(true);

				}

			}
		};





		from_button = (Button) findViewById(R.id.from_button);
		until_button = (Button) findViewById(R.id.until_button);
		//preference_button = (Button) findViewById(R.id.preference_button);
		me_button = (Button) findViewById(R.id.me_button);


		/*preference_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isConnectedToInternet()){
					Intent gotoPreferenceActivityIntent = new Intent("com.example.dinnertogetherapp.PREFERENCEACTIVITY");
					startActivity(gotoPreferenceActivityIntent);
				}
				else{
					Toast.makeText(getApplicationContext(), "You are not conneceted to Internet, please check.", Toast.LENGTH_SHORT).show();
				}

			}
		});
		 */

		/*availability_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isConnectedToInternet()){
					Intent gotoPreferenceActivityIntent = new Intent("com.example.dinnertogetherapp.AVAILABILITYACTIVITY");
					startActivity(gotoPreferenceActivityIntent);
				}
				else{
					Toast.makeText(getApplicationContext(), "You are not conneceted to Internet, please check.", Toast.LENGTH_SHORT).show();
				}


			}
		});*/


		from_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				hideKeyboard();
				// TODO Auto-generated method stub
				/*		Dialog date_choose_dialog = new Dialog(MyInfoActivity.this);

				date_choose_dialog.setContentView(R.layout.date_time_picker);



				TimePicker timePicker = (TimePicker) findViewById(R.id.time_picker);
				date_choose_dialog.show();*/



				AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MyInfoActivity.this);				
				LayoutInflater factory = LayoutInflater.from(MyInfoActivity.this);
				View deleteDialogView = factory.inflate(
						R.layout.date_time_picker, null);
				dialogBuilder.setView(deleteDialogView);

				date_picker = (DatePicker) deleteDialogView.findViewById(R.id.date_picker);
				time_picker = (TimePicker) deleteDialogView.findViewById(R.id.time_picker);

				dialogBuilder.setCancelable(true);
				dialogBuilder.setTitle("Set Date and Time");
				dialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						Calendar currentCal = Calendar.getInstance();

						int curYear = currentCal.get(Calendar.YEAR);
						int curMonth = currentCal.get(Calendar.MONTH);
						int curDay = currentCal.get(Calendar.DAY_OF_MONTH);
						int curHour = currentCal.get(Calendar.HOUR_OF_DAY);
						int curMin = currentCal.get(Calendar.MINUTE);

						Date currentDate = new Date(curYear, curMonth, curDay , curHour, curMin);



						SimpleDateFormat dateFormat = new SimpleDateFormat("yy/MM/dd h:mm a");
						SimpleDateFormat dayOfWeekFormat = new SimpleDateFormat("EE");
						Date dayOfWeekDate = new Date(date_picker.getYear(), date_picker.getMonth(), date_picker.getDayOfMonth() - 1);

						String dayOfWeekText = dayOfWeekFormat.format(dayOfWeekDate);


						FROM_DATE = new Date(date_picker.getYear(), date_picker.getMonth(), date_picker.getDayOfMonth(),time_picker.getCurrentHour(), time_picker.getCurrentMinute());



						if (FROM_DATE.before(currentDate)){
							Toast.makeText(getApplicationContext(), "The date you choose is before the current date, please choose the date after today.", Toast.LENGTH_LONG).show();
							dialog.cancel();
						}
						else{



							if (isConnectedToInternet()){

								START_TIME = dateFormat.format(FROM_DATE);
								START_TIME = dayOfWeekText + ", " + START_TIME;
								from_date_textView.setText(START_TIME);

								local_user_editor = local_user_information.edit();
								local_user_editor.putString("start_year", String.valueOf(date_picker.getYear()));
								local_user_editor.putString("start_month", String.valueOf(date_picker.getMonth()));
								local_user_editor.putString("start_day", String.valueOf(date_picker.getDayOfMonth()));
								local_user_editor.putString("start_hour", String.valueOf(time_picker.getCurrentHour()));
								local_user_editor.putString("start_min", String.valueOf(time_picker.getCurrentMinute()));
								local_user_editor.putString("start_time", START_TIME);
								local_user_editor.commit();

								updateStartTime();
							}
							else{
								Toast.makeText(getApplicationContext(), "You are not conneceted to Internet, please check.", Toast.LENGTH_SHORT).show();
							}

						}




					}
				});

				dialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

						dialog.cancel();


					}
				});

				AlertDialog dialog = dialogBuilder.create();
				dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;

				dialog.show();


			}
		});



		until_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				hideKeyboard();
				// TODO Auto-generated method stub
				/*		Dialog date_choose_dialog = new Dialog(MyInfoActivity.this);

				date_choose_dialog.setContentView(R.layout.date_time_picker);
				date_choose_dialog.setTitle("Set Date and Time");
				 */

				AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MyInfoActivity.this);				
				LayoutInflater factory = LayoutInflater.from(MyInfoActivity.this);
				View deleteDialogView = factory.inflate(
						R.layout.date_time_picker, null);

				date_picker = (DatePicker) deleteDialogView.findViewById(R.id.date_picker);
				time_picker = (TimePicker) deleteDialogView.findViewById(R.id.time_picker);


				dialogBuilder.setView(deleteDialogView);
				dialogBuilder.setCancelable(true);
				dialogBuilder.setTitle("Set Date and Time");
				dialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

						SimpleDateFormat dateFormat = new SimpleDateFormat("yy/MM/dd h:mm a");

						SimpleDateFormat dayOfWeekFormat = new SimpleDateFormat("EE");
						Date dayOfWeekDate = new Date(date_picker.getYear(), date_picker.getMonth(), date_picker.getDayOfMonth() - 1);

						String dayOfWeekText = dayOfWeekFormat.format(dayOfWeekDate);


						UNTIL_DATE = new Date(date_picker.getYear(), date_picker.getMonth(), date_picker.getDayOfMonth(),time_picker.getCurrentHour(), time_picker.getCurrentMinute());

						if (UNTIL_DATE.before(FROM_DATE)){
							Toast.makeText(getApplicationContext(), "Please choose the date after from date.", Toast.LENGTH_LONG).show();
							dialog.cancel();
						}
						else{

							if (isConnectedToInternet()){



								END_TIME = dateFormat.format(UNTIL_DATE);
								END_TIME = dayOfWeekText + ", " + END_TIME;

								until_date_textView.setText(END_TIME);


								local_user_editor = local_user_information.edit();
								local_user_editor.putString("end_year", String.valueOf(date_picker.getYear()));
								local_user_editor.putString("end_month", String.valueOf(date_picker.getMonth()));
								local_user_editor.putString("end_day", String.valueOf(date_picker.getDayOfMonth()));
								local_user_editor.putString("end_hour", String.valueOf(time_picker.getCurrentHour()));
								local_user_editor.putString("end_min", String.valueOf(time_picker.getCurrentMinute()));
								local_user_editor.putString("end_time", END_TIME);
								local_user_editor.commit();




								updateEndTime();


								if (!isStartAndEndTimeBeforeNow()){

									make_me_available_switch.setEnabled(true);


								}
							}
							else{
								Toast.makeText(getApplicationContext(), "You are not conneceted to Internet, please check.", Toast.LENGTH_SHORT).show();
							}


						}









					}
				});

				dialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

						dialog.cancel();

					}
				});

				AlertDialog dialog = dialogBuilder.create();
				dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
				dialog.show();


			}
		});




		me_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent gotoMeSettingActivityIntent = new Intent("yicheng.dinnertogetherapp.MESETTINGACTIVITY");

				startActivity(gotoMeSettingActivityIntent);
			}
		});


/*
		log_out_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				local_user_editor = local_user_information.edit();

				//clear local user data in shared preference
				//local_user_editor.putString("PhoneNumber", "default");
				local_user_editor.putString("Password", "default");
				local_user_editor.putBoolean("notRegistered", true);	


				local_user_editor.putString("Preference", "Preference");
				local_user_editor.putString("start_time", "0 : 00 AM");
				local_user_editor.putString("end_time", "0 : 00 PM");
				local_user_editor.commit();

				//new loadDataBase().execute();
				Toast.makeText(MyInfoActivity.this,String.valueOf(local_user_information.getString("PhoneNumber", "phonenumber") ), Toast.LENGTH_SHORT).show();
				Toast.makeText(MyInfoActivity.this,String.valueOf(local_user_information.getString("Password", "password") ), Toast.LENGTH_SHORT).show();
				Toast.makeText(MyInfoActivity.this,String.valueOf(local_user_information.getBoolean("notRegistered", false) ), Toast.LENGTH_SHORT).show();


				MyInfoActivity.this.stopService(new Intent(MyInfoActivity.this, DateUpdateService.class));

				MyInfoActivity.this.stopService(new Intent(MyInfoActivity.this, BackgroundDateUpdateService.class));

				//if (!PHONE_NUMBER.equals(PRIMARY_PHONE_NUMBER)){
				//MyInfoActivity.this.stopService(new Intent(MyInfoActivity.this, UserInfoUpdateService.class));
				//}




				Intent gotoLogInViewIntent = new Intent("yicheng.dinnertogetherapp.LOGINACTIVITY");
				startActivity(gotoLogInViewIntent);

				finish();

			}
		});*/


	}





	public void updateOnlineStatus(final boolean isChecked){
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");
		NICKNAME = local_user_information.getString("Nickname", "default");
		local_user_editor = local_user_information.edit();

		make_me_available_switch.setEnabled(false);


		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new Thread(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (isChecked){
							local_user_editor = local_user_information.edit();
							local_user_editor.putString("online_offline", "online");
							local_user_editor.commit();

							SimpleDB.updateSingleAttribute(clientManager, PHONE_NUMBER, SimpleDB.ONLINE_ITEM, SimpleDB.ONLINE_ATTRIBUTE, "online");

							HashMap<String,String> myFriendList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM);

							myFriendList.remove("2060000000");
							myFriendList.remove("Name");

							String [] myFriendNumberList =  myFriendList.keySet().toArray(new String[0]);		

							HashMap<String, String> beUnavailableToFriendsList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.BE_UNAVAILABLE_TO_LIST_ITEM);





							for (int i = 0; i < myFriendNumberList.length; i++){

								if (!beUnavailableToFriendsList.containsKey(myFriendNumberList[i])){
									HashMap<String, String> onlineFriendList = SimpleDB.getAttributesForItem(clientManager, myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM);
									onlineFriendList.put(PHONE_NUMBER, NICKNAME);
									SimpleDB.deleteItem(clientManager, myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM);
									SimpleDB.updateAttributesForItem(clientManager, myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM, onlineFriendList);

									HashMap<String, String> offlineFriendList = SimpleDB.getAttributesForItem(clientManager, myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
									offlineFriendList.remove(PHONE_NUMBER);
									SimpleDB.deleteItem(clientManager, myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
									SimpleDB.updateAttributesForItem(clientManager, myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM, offlineFriendList);
								}
							}

							myFriendList.put("2060000000", "dummyUser");

							SimpleDB.deleteItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM);

							SimpleDB.updateAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM, myFriendList);


							/*		local_user_editor.putString("online", "online");
							local_user_editor.commit();*/

						}
						else{
							local_user_editor = local_user_information.edit();
							local_user_editor.putString("online_offline", "offline");
							local_user_editor.commit();
							SimpleDB.updateSingleAttribute(clientManager, PHONE_NUMBER, SimpleDB.ONLINE_ITEM, SimpleDB.ONLINE_ATTRIBUTE, "offline");


							HashMap<String,String> myFriendList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM);

							myFriendList.remove("2060000000");
							myFriendList.remove("Name");


							String [] myFriendNumberList =  myFriendList.keySet().toArray(new String[0]);		


							for (int i = 0; i < myFriendNumberList.length; i++){

								HashMap<String, String> onlineFriendList = SimpleDB.getAttributesForItem(clientManager,myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM);
								onlineFriendList.remove(PHONE_NUMBER);
								SimpleDB.deleteItem(clientManager, myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM);
								SimpleDB.updateAttributesForItem(clientManager, myFriendNumberList[i], SimpleDB.ONLINE_FRIEND_LIST_ITEM, onlineFriendList);

								HashMap<String, String> offlineFriendList = SimpleDB.getAttributesForItem(clientManager,myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
								offlineFriendList.put(PHONE_NUMBER, NICKNAME);
								SimpleDB.deleteItem(clientManager, myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM);
								SimpleDB.updateAttributesForItem(clientManager, myFriendNumberList[i], SimpleDB.OFFLINE_FRIEND_LIST_ITEM, offlineFriendList);
							}

							myFriendList.put("2060000000", "dummyUser");


							SimpleDB.deleteItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM);

							SimpleDB.updateAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM, myFriendList);

							/*	local_user_editor.putString("online", "offline");
							local_user_editor.commit();*/
						}



						Message msg = Message.obtain();
						msg.what = 1;
						handler.sendMessage(msg);



					}




				}).start();
			}

		});





	}














	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		moveTaskToBack(true);
	}



	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK ) {
			//preventing default implementation previous to 
			//android.os.Build.VERSION_CODES.ECLAIR


			moveTaskToBack(true);


			return false;
		}     
		return super.onKeyDown(keyCode, event);    

	}



	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();


	}





	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		/*updatePreferenceAndAvailabilityDisplay();*/
	}


	/*private void updatePreferenceAndAvailabilityDisplay(){
		PREFERENCE = local_user_information.getString("Preference", "Preference");

		START_TIME = local_user_information.getString("start_time", "0 : 00 AM");
		END_TIME = local_user_information.getString("end_time", "0 : 00 PM");

		//preference_textView.setText(PREFERENCE);
		//availability_textView.setText(START_TIME + " - " + END_TIME);
	}*/


	private void updateOnlineSwitchDisplay(){
		ONLINE = local_user_information.getString("online_offline", "default");
		if (ONLINE.equals("online")){
			make_me_available_switch.setChecked(true);
		}
		else if (ONLINE.equals("offline")){
			make_me_available_switch.setChecked(false);
		}
	}



	private boolean isConnectedToInternet(){
		ConnectivityManager connectivityManager = 
				(ConnectivityManager)MyInfoActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo wifi_network = 
				connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo mobile_network = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

		//Only for testing
		return wifi_network.isConnectedOrConnecting() || mobile_network.isConnectedOrConnecting();
		/*return  mobile_network.isConnectedOrConnecting();*/
	}

	/*@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();

		preference_textView.setText(PREFERENCE);
		availability_textView.setText(AVAILABILITY);
	}
	 */

	private void hideKeyboard(){
		if(getCurrentFocus()!=null) {
			InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
			preference_editText.setCursorVisible(false);
		}
	}

	public static void updatePreferenceDisplay(){
		PREFERENCE = local_user_information.getString("Preference", "My Preference");
		preference_editText.setText(PREFERENCE);
		preference_character_textView.setText(String.valueOf(95 - PREFERENCE.length()));
	}

	private void updatePreference(){
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");
		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new Thread(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub
						SimpleDB.updateSingleAttribute(clientManager, PHONE_NUMBER,SimpleDB.PREFERENCE_ITEM, SimpleDB.PREFERENCE_ATTRIBUTE, preference_editText.getText().toString());

					}

				}).start();
			}

		});
	}


	private boolean isStartAndEndTimeBeforeNow(){
		Calendar currentCal = Calendar.getInstance();

		int curYear = currentCal.get(Calendar.YEAR);
		int curMonth = currentCal.get(Calendar.MONTH);
		int curDay = currentCal.get(Calendar.DAY_OF_MONTH);
		int curHour = currentCal.get(Calendar.HOUR_OF_DAY);
		int curMin = currentCal.get(Calendar.MINUTE);

		Date currentDate = new Date(curYear, curMonth, curDay , curHour , curMin);

		String fromYear = local_user_information.getString("start_year", "0000");
		String fromMonth = local_user_information.getString("start_month", "00");
		String fromDay = local_user_information.getString("start_day", "00");
		String fromHour = local_user_information.getString("start_hour", "00");
		String fromMin = local_user_information.getString("start_min", "00");


		FROM_DATE = new Date(Integer.parseInt(fromYear), Integer.parseInt(fromMonth), Integer.parseInt(fromDay), Integer.parseInt(fromHour), Integer.parseInt(fromMin));


		String untilYear = local_user_information.getString("end_year", "0000");
		String untilMonth = local_user_information.getString("end_month", "00");
		String untilDay = local_user_information.getString("end_day", "00");
		String untilHour = local_user_information.getString("end_hour", "00");
		String untilMin = local_user_information.getString("end_min", "00");


		UNTIL_DATE = new Date(Integer.parseInt(untilYear), Integer.parseInt(untilMonth), Integer.parseInt(untilDay), Integer.parseInt(untilHour), Integer.parseInt(untilMin));


		return FROM_DATE.before(currentDate) && UNTIL_DATE.before(currentDate);

	}


	private void updateFromDateDisplay(){
		Calendar currentCal = Calendar.getInstance();

		int curYear = currentCal.get(Calendar.YEAR);
		int curMonth = currentCal.get(Calendar.MONTH);
		int curDay = currentCal.get(Calendar.DAY_OF_MONTH);
		int curHour = currentCal.get(Calendar.HOUR_OF_DAY);
		int curMin = currentCal.get(Calendar.MINUTE);

		Date currentDate = new Date(curYear, curMonth, curDay , curHour , curMin);


		/*	local_user_editor = local_user_information.edit();	
		local_user_editor.remove("start_year");
		local_user_editor.remove("start_month");
		local_user_editor.remove("start_day");
		local_user_editor.remove("start_hour");
		local_user_editor.remove("start_min");
		local_user_editor.commit();


		local_user_editor.remove("end_year");
		local_user_editor.remove("end_month");
		local_user_editor.remove("end_day");
		local_user_editor.remove("end_hour");
		local_user_editor.remove("end_min");
		local_user_editor.commit();*/



		String fromYear = local_user_information.getString("start_year", "0000");
		String fromMonth = local_user_information.getString("start_month", "00");
		String fromDay = local_user_information.getString("start_day", "00");
		String fromHour = local_user_information.getString("start_hour", "00");
		String fromMin = local_user_information.getString("start_min", "00");


		FROM_DATE = new Date(Integer.parseInt(fromYear), Integer.parseInt(fromMonth), Integer.parseInt(fromDay), Integer.parseInt(fromHour), Integer.parseInt(fromMin));


		String untilYear = local_user_information.getString("end_year", "0000");
		String untilMonth = local_user_information.getString("end_month", "00");
		String untilDay = local_user_information.getString("end_day", "00");
		String untilHour = local_user_information.getString("end_hour", "00");
		String untilMin = local_user_information.getString("end_min", "00");


		UNTIL_DATE = new Date(Integer.parseInt(untilYear), Integer.parseInt(untilMonth), Integer.parseInt(untilDay), Integer.parseInt(untilHour), Integer.parseInt(untilMin));


		SimpleDateFormat dateFormat = new SimpleDateFormat("yy/MM/dd h:mm a");
		SimpleDateFormat dayOfWeekFormat = new SimpleDateFormat("EE");
		Date dayOfWeekDate = new Date(curYear, curMonth, curDay - 1);

		String dayOfWeekText = dayOfWeekFormat.format(dayOfWeekDate);

		String current_time = dateFormat.format(currentDate);

		START_TIME = local_user_information.getString("start_time", dayOfWeekText + ", " + current_time);
		//START_TIME = dayOfWeekText + ", " + current_time;

		from_date_textView.setText(START_TIME);

		END_TIME = local_user_information.getString("end_time", dayOfWeekText + ", " + current_time);
		until_date_textView.setText(END_TIME);




		/*	String from_time = dateFormat.format(FROM_DATE);


		from_date_textView.setText(current_time + "   " + from_time);

	   String until_time = dateFormat.format(UNTIL_DATE);


		until_date_textView.setText(current_time + "   " + until_time);*/

		/*
		if (FROM_DATE.before(currentDate)){

			//from_date_textView.setText(dayOfWeekText + ", " + START_TIME);
			//START_TIME = dateFormat.format(FROM_DATE);
			START_TIME = dayOfWeekText + ", " + current_time;
			from_date_textView.setText(START_TIME);

			local_user_editor = local_user_information.edit();
			local_user_editor.putString("start_year", String.valueOf(curYear));
			local_user_editor.putString("start_month", String.valueOf(curMonth));
			local_user_editor.putString("start_day", String.valueOf(curDay));
			local_user_editor.putString("start_hour", String.valueOf(curHour));
			local_user_editor.putString("start_min", String.valueOf(curMin));
			local_user_editor.putString("start_time", START_TIME);
			local_user_editor.commit();

			//FROM_DATE= new Date(curYear, curMonth, curDay , curHour, curMin);

			updateStartTime();

		}
		else{
			START_TIME = local_user_information.getString("start_time", dayOfWeekText + ", " + current_time);
		//START_TIME = dayOfWeekText + ", " + current_time;

			from_date_textView.setText(START_TIME);
			//from_date_textView.setText(START_TIME + " " + fromMonth + " " + fromDay + " " + fromHour + " " + fromMin);

		}
		 */

		/*if (UNTIL_DATE.before(currentDate)){
			//until_date_textView.setText(dayOfWeekText + ", " + START_TIME);

			END_TIME = dayOfWeekText + ", " + current_time;
			until_date_textView.setText(END_TIME);

			local_user_editor = local_user_information.edit();
			local_user_editor.putString("end_year", String.valueOf(curYear));
			local_user_editor.putString("end_month", String.valueOf(curMonth));
			local_user_editor.putString("end_day", String.valueOf(curDay));
			local_user_editor.putString("end_hour", String.valueOf(curHour));
			local_user_editor.putString("end_min", String.valueOf(curMin));
			local_user_editor.putString("end_time", END_TIME);
			local_user_editor.commit();

			//UNTIL_DATE = new Date(curYear, curMonth, curDay , curHour, curMin);

			updateOnlineStatus(false);
			//updateEndTime();

		}
		else{
			END_TIME = local_user_information.getString("end_time", dayOfWeekText + ", " + current_time);
			until_date_textView.setText(END_TIME);
		}
		 */


	}


	@Override
	protected void onStart() {
		// TODO Auto-generated method stub



		super.onStart();

		broadcastReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context ctx, Intent intent)
			{

				if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0){
					updateOnlineSwitchDisplay();

					//updateFromDateDisplay();

					//updateOnlineStatus();

				}

			}
		};

		registerReceiver(broadcastReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));



	}





	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();




	}


	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		/*		
		MyInfoActivity.this.stopService(new Intent(MyInfoActivity.this, DateUpdateService.class));
		MyInfoActivity.this.startService(new Intent(MyInfoActivity.this, BackgroundDateUpdateService.class));*/


	}





	private void updateStartTime(){
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");
		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new Thread(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub
						SimpleDB.updateSingleAttribute(clientManager, PHONE_NUMBER,SimpleDB.AVAILABILITY_ITEM, SimpleDB.START_TIME_ATTRIBUTE, START_TIME);

					}

				}).start();
			}

		});
	}


	private void updateEndTime(){
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");
		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new Thread(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub

						SimpleDB.updateSingleAttribute(clientManager, PHONE_NUMBER,SimpleDB.AVAILABILITY_ITEM, SimpleDB.END_TIME_ATTRIBUTE, END_TIME);
					}

				}).start();
			}

		});
	}

	private boolean isMyServiceRunning() {
		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
			if (UserInfoUpdateService.class.getName().equals(service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}







}
